package com.erdos.thb.tools;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;

public class QrCodeUtil {
	
	
	public static WritableImage get(String code) throws Exception {
		StringBuilder content =new StringBuilder();// 内容
		content.append(code);
		int width = 100; // 图像宽度
		int height = 100; // 图像高度
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content.toString(),
				BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵

		WritableImage image = new WritableImage(width, height);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				Color c = null;
				if(bitMatrix.get(x, y)){
					c = Color.rgb(0, 0, 0);
				}else{
					c = Color.rgb(255, 255, 255);
				}
				
				image.getPixelWriter().setColor(x, y, c);
			}
		}
		return image;
	}
	
	public static BufferedImage get1(String code) throws Exception {
		StringBuilder content =new StringBuilder();// 内容
		content.append(code);
		int width = 200; // 图像宽度
		int height = 200; // 图像高度
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content.toString(),
				BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵

		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
						: 0xFFFFFFFF);
				System.out.println(image.getRGB(x, y));
			}
		}
		return image;
	}
}
